<?php

abstract class HeaderManagerBase {

    protected $fileBasePath = "images/header/";

    abstract public function saveFile($placeId, $tmpFile); // insert & replace file

    abstract public function delHeaerByPlaceId($placeId); // remove images file & remove data db

    abstract public function getAbsoluteHeaderPath($placeId); // get location images
}

class HeaderManager extends HeaderManagerBase {

    public $message;
    public $Debug;

    public function saveFile($placeId, $tmpFile) {
        if (!$tmpFile['type'] == "image/png") // Check file type
            return false;

        $picture = DbCoverimg::model()->findByPk($placeId);
        if (!is_array($picture))
            $picture->ID_Cover = $placeId;

        $picture->Image_Location = getAbsoluteHeaderPath($placeId) . $tmpFile['name']; // Get Ready value Location Image
        if (!upload_image($tmpFile)): // Check & Update & get Debug
            $this->message = "Upload Error";
            return false;
        endif;
        if ($picture->save()):
            $this->message = "Succ";
        else:
            $this->message = "Fail";
            return false;
        endif;
    }

    public function delHeaerByPlaceId($placeId) {
        // select Image_Location & Delete
        $picture = DbCoverimg::model()->findByPk($placeId);
        if (is_file($get_loc = $picture->Image_Location)):
            $picture->delete();
            unlink($get_loc);
        else:
            $this->message = "Not file.";
            return false;
        endif;
    }

    public function getAbsoluteHeaderPath($placeId) {
        $get_url = "{$_SERVER['SERVER_NAME']}/{$this->fileBasePath}{$placeId}";
        return $get_url;
    }

    private function upload_image($tmpFile) {
        // save-as
        $uploadedFile = CUploadedFile::getInstance($tmpFile, 'image');
        $uploadedFile->saveAs(Yii::app()->basePath . "{$this->fileBasePath}" . $tmpFile['name']);
        return true;
    }

}